#include "SockStream.h"
#include "SockAcceptor.h"

#include <errno.h>
#include <assert.h>
#include <stdio.h>
#include <sys/epoll.h>
#include <iostream>

int main ()
{
    InetAddr local_addr (8889);

    SockStream peer;
    SockAcceptor acceptor;
    if (acceptor.open (local_addr) != 0)
    {
	std::cout << errno << std::endl;
	perror ("open");
	return 0;
    }
    InetAddr remote_addr;
    if (acceptor.accept (peer, &remote_addr) != 0)
    {
	std::cout << errno << std::endl;
	perror ("accept");
	return 0;
    }
    char buff[512] = {0};
    int ep_fd = epoll_create (20);
    struct epoll_event ep, evs[20];
    ep.events  = EPOLLIN;
    ep.data.fd = peer.handle ();
    epoll_ctl (ep_fd, EPOLL_CTL_ADD, peer.handle (), &ep);

    while (1)
    {
	int ret = epoll_wait (ep_fd, evs, 20, 2*1000);
	if (ret <= 0)
	{
	    perror ("epoll_wait");
	    std::cout << "timeout of error, ret = " << ret << "errno = " << errno << std::endl << std::endl;
	}else
	{
	    std::cout << "readable\n" ;
	    evs[0].events = EPOLLONESHOT;
	    assert (evs[0].data.fd == peer.handle ());
	    epoll_ctl (ep_fd, EPOLL_CTL_MOD, evs[0].data.fd, &evs[0]);
	    memset (buff, 0, sizeof(buff));
	    ret = peer.recv (buff, 512);
	    if (ret == 0)
	    {
		std::cout << "client close\n";
		break;
	    }
	    std::cout << buff << std::endl;
	    peer.send(buff, ret);
	    evs[0].events = EPOLLIN;
	    assert (evs[0].data.fd == peer.handle ());
	    epoll_ctl (ep_fd, EPOLL_CTL_MOD, evs[0].data.fd, &evs[0]);
	}
    }
    peer.close ();
    return 0;
}
